#!/bin/sh
set -e
if [ -z "$SYSROOT" ]; then export SYSROOT="$(realpath "$(dirname "$0")/../sysroot")"; fi
if [ -z "$LLVMDIR" ]; then export LLVMDIR="$(realpath "$(dirname "$0")/../llvm-project")"; fi
if [ -f "$SYSROOT/bin/musl-gcc" ]; then export CC="$SYSROOT/bin/musl-gcc"; fi
if [ -f "$SYSROOT/bin/musl-clang" ]; then export CC="$SYSROOT/bin/musl-clang"; fi

rm -rf build0
mkdir build0
cd build0
export ASMFLAGS="-w -mcmodel=large -mstack-protector-guard=global -fno-pic -fno-pie -fcf-protection=none"
export CFLAGS="-w -mcmodel=large -mstack-protector-guard=global -fno-pic -fno-pie -fcf-protection=none"
export CXXFLAGS="-w -mcmodel=large -mstack-protector-guard=global -fno-pic -fno-pie -fcf-protection=none -fno-use-cxa-atexit"
export LDFLAGS="-no-pie"

# libunwind cmake script never actually does enable_language(ASM) or project(... ASM) it would seem
# this is probably due to this being intended to be called from another script
# but this ends up breaking our standalone building of libunwind
# there isn't a simple fix with a command line option, so...

printf "%s\n%s\n%s\n" "cmake_minimum_required(VERSION 3.20.0)" "project(libunwind C CXX ASM)" "add_subdirectory($LLVMDIR/libunwind libunwind)" > CMakeLists.txt

cmake \
	-DCMAKE_ASM_COMPILER="$CC" \
	-DCMAKE_C_COMPILER="$CC" \
	-DCMAKE_CXX_COMPILER="$CC" \
	-DLIBUNWIND_ENABLE_SHARED=OFF \
	-DLIBUNWIND_USE_COMPILER_RT=ON \
	-DLIBUNWIND_IS_BAREMETAL=ON \
	-DCMAKE_INSTALL_PREFIX="$SYSROOT" \
	.
